package service.impl;

import dao.StudentDao;
import dao.impl.StudentDaoImpl;
import entity.Student;
import service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {
    private static final StudentDao studentDao = new StudentDaoImpl();

    @Override
    public Boolean register(Student student) {
        // 先判断用户名是否已经存在
        Student selectByName = studentDao.selectByName(student.getName());
        if (selectByName != null) {
            throw new RuntimeException("用户名已经存在");
        }
        // 判断用户邮箱是否已经存在
        Student selectByEmail = studentDao.selectByEmail(student.getEmail());
        if (selectByEmail != null) {
            throw new RuntimeException("邮箱已经存在");
        }
        // 获取最新的id
        Integer lastId = studentDao.selectLastId();
        // 插入数据
        student.setId(lastId + 1);
        return studentDao.register(student);
    }

    @Override
    public Student login(String name, String password) {
        Student result = studentDao.selectWithNameAndPassword(name, password);
        if (result == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        return result;
    }

    @Override
    public List<Student> selectAllStudents() {
        return studentDao.selectAllStudents();
    }

    @Override
    public List<Student> selectStudentLikeName(String name) {
        return studentDao.selectStudentLikeName(name);
    }
}
